package com.lei.mq.service.impl;

import javax.jms.Queue;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import com.lei.mq.config.ScheduleMessagePostProcessor;
import com.lei.mq.entity.ProdEntity;
import com.lei.mq.enums.ApiErrorEnum;
import com.lei.mq.enums.OrderStatusEnum;
import com.lei.mq.exception.ApiException;
import com.lei.mq.mapper.OrderListMapper;
import com.lei.mq.service.OrderListService;
import com.lei.mq.util.JsonUtil;
import com.lei.mq.util.SnowFlakeUtil;

@Service
public class OrderListSerivceImpl implements OrderListService {
	private Logger LOGGER = LogManager.getLogger();
	@Autowired
	private OrderListMapper orderListMapper;
	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	private Queue orderTimeOutClose;
	
	@Autowired
	private Queue addJdQueue;
	
	public void sendJd(String msg) {
		LOGGER.info("消息sendJd：[{}]发送成功！",msg);
		this.jmsTemplate.convertAndSend(this.addJdQueue, msg);
	}
	public void sendOrderTimeOutClose(Object msg) {
		//延时30秒发送
		jmsTemplate.convertAndSend(this.orderTimeOutClose,msg, new ScheduleMessagePostProcessor(60 * 1000));
		LOGGER.info("消息sendOrderTimeOutClose：[{}]发送成功！",msg);

	}
	
	@Override
	public ProdEntity addOrder(ProdEntity record) {
		// TODO Auto-generated method stub
		record.setOrderNumber(String.valueOf(SnowFlakeUtil.getSnowFlakeUtil().nextId()));
		// 待付款
		record.setOrderStatus(OrderStatusEnum.WAIT_PAYMENT.getCode());
		orderListMapper.addOrder(record);
		sendOrderTimeOutClose(record.getOrderNumber());
		return null;
	}

	@Override
	public ProdEntity payment(String orderNumber) {
		ProdEntity prodEntity = checkOrderExists(orderNumber);
		// 检查状态是否为待付款
		if (!OrderStatusEnum.WAIT_PAYMENT.getCode().equals(prodEntity.getOrderStatus())) {
			throw new ApiException(ApiErrorEnum.ERROR_1002);
		}
		ProdEntity entity = new ProdEntity();
		entity.setOrderNumber(orderNumber);
		entity.setOrderStatus(OrderStatusEnum.PAYMENT.getCode());
		orderListMapper.update(entity);
		sendJd(JsonUtil.beanToJson(prodEntity));
		return null;
	}

	@Override
	public void closeTheOrder(String orderNumber) {
		ProdEntity prodEntity = checkOrderExists(orderNumber);
		// 检查状态是否为待付款
		if (!OrderStatusEnum.WAIT_PAYMENT.getCode().equals(prodEntity.getOrderStatus())) {
			throw new ApiException(ApiErrorEnum.ERROR_1002);
		}
		ProdEntity entity = new ProdEntity();
		entity.setOrderNumber(orderNumber);
		entity.setOrderStatus(OrderStatusEnum.CLOSE.getCode());
		orderListMapper.update(entity);
	}

	private ProdEntity checkOrderExists(String orderNumber) {
		// 检查订单是否存在
		ProdEntity prodEntity = orderListMapper.selectByOrderNumber(orderNumber);
		if (prodEntity == null) {
			throw new ApiException(ApiErrorEnum.ERROR_1001);
		}
		return prodEntity;
	}

}
